package com.qf.mybatisplus.test;

import cn.hutool.http.HttpUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class BiAnTuSpider {


    public static void main(String[] args) {
        String cookie = "cf_clearance=24zYppFC_rzjmzJMwhSw.YVYJvnUK3qNKyTWA6qz_RM-1732285910-1.2.1.1-MZUCT5cxrTll4LSmYmVxnZyT5rIqFXf9RLJ84ick.0ncGyb5xIJzlyZbptGkfy9glnuX6OGOBgHvuyPjgQrUq4FDbSiqOGuJRs8puheMHFhRMmvol_3CoXKCQzv4iTRGg4EwqOqwhi8PsN.uEDQ3FXJEsIDKovUja0VGlRosTMHv8ronj1HoFgipeFQ8yXirSefFM9PmYtNRTu_zN2ayBg9z4FIb6XgLQjzOCmSWnNfqAhf5tVSp3VykMrP.SX2rWiseBMuvnHhVL92bU9pA67c77SW4D2KidTWxDcQ4ATcqwJm1LgvVva2nbF4VzZ1TT9siZX.1RLwEcn.TZgQz8DoPDq7yXieqvbD6QHNBmO0ui3BhXwwdspsYlmJ9x3iFcBus2naEGx8ST1pV6XZkCEBK_PvICtZvU7Zrx5XIo980WVraM5om7CgHNkHPZc.P; zkhanecookieclassrecord=%2C70%2C; PHPSESSID=nee118a9abp6f1je8g4pnreab2; zkhanmlusername=qq_%C1%AB%B0%A2%D0%DE%B1%B4%B6%FB643; zkhanmluserid=4887420; zkhanmlgroupid=1; zkhanmlrnd=Nts1EwDrnEJU4sN0AONq; zkhanmlauth=d0c3fcda37196fd2e14f3d52a28daead";

        BiAnTuSpider biAnTuSpider = new BiAnTuSpider();
//        biAnTuSpider.getPhoto();

        String photoId = "34056";
        biAnTuSpider.getPhotoById(cookie,photoId);



    }

    public void getPhoto(){
        BiAnTuSpider biAnTuSpider = new BiAnTuSpider();

        for (int i = 29900; i < 29999; i++) {
            String tokenUrl = "https://pic.netbian.com/e/extend/downpic.php?id=" + i;


            String cookie = "cf_clearance=24zYppFC_rzjmzJMwhSw.YVYJvnUK3qNKyTWA6qz_RM-1732285910-1.2.1.1-MZUCT5cxrTll4LSmYmVxnZyT5rIqFXf9RLJ84ick.0ncGyb5xIJzlyZbptGkfy9glnuX6OGOBgHvuyPjgQrUq4FDbSiqOGuJRs8puheMHFhRMmvol_3CoXKCQzv4iTRGg4EwqOqwhi8PsN.uEDQ3FXJEsIDKovUja0VGlRosTMHv8ronj1HoFgipeFQ8yXirSefFM9PmYtNRTu_zN2ayBg9z4FIb6XgLQjzOCmSWnNfqAhf5tVSp3VykMrP.SX2rWiseBMuvnHhVL92bU9pA67c77SW4D2KidTWxDcQ4ATcqwJm1LgvVva2nbF4VzZ1TT9siZX.1RLwEcn.TZgQz8DoPDq7yXieqvbD6QHNBmO0ui3BhXwwdspsYlmJ9x3iFcBus2naEGx8ST1pV6XZkCEBK_PvICtZvU7Zrx5XIo980WVraM5om7CgHNkHPZc.P; zkhanecookieclassrecord=%2C70%2C; PHPSESSID=nee118a9abp6f1je8g4pnreab2; zkhanmlusername=qq_%C1%AB%B0%A2%D0%DE%B1%B4%B6%FB643; zkhanmluserid=4887420; zkhanmlgroupid=1; zkhanmlrnd=Nts1EwDrnEJU4sN0AONq; zkhanmlauth=d0c3fcda37196fd2e14f3d52a28daead";
            String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";


            String token = null;
            try {
                token = biAnTuSpider.spider(tokenUrl,cookie,userAgent);
            } catch (Exception e) {
                System.out.println("获取token失败:" + i);
                continue;
            }

            try {
                biAnTuSpider.downLoad(token,cookie,userAgent);
            } catch (Exception e) {
                System.out.println("下载图片失败：" + i);
                e.printStackTrace();
                continue;
            }
        }
    }

    public void getPhotoById(String cookie,String photoId){
        BiAnTuSpider biAnTuSpider = new BiAnTuSpider();

        String tokenUrl = "https://pic.netbian.com/e/extend/downpic.php?id=" + photoId;


        String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";


        String token = null;
        try {
            token = biAnTuSpider.spider(tokenUrl,cookie,userAgent);
        } catch (Exception e) {
            System.out.println("获取token失败:" + photoId);

        }

        try {
            biAnTuSpider.downLoad(token,cookie,userAgent);
        } catch (Exception e) {
            System.out.println("下载图片失败：" + photoId);
            e.printStackTrace();
        }
    }

    public String spider(String tokenUrl,String cookie,String userAgent){

        String getTokenRes = HttpUtil.createGet(tokenUrl).header("cookie",cookie).header("user-agent",userAgent).execute().body();
        System.out.println("获取token接口响应：" + getTokenRes);
        JSONObject tokenResObj = JSONUtil.parseObj(getTokenRes);
        String picStr = tokenResObj.getStr("pic");
        String[] split = picStr.split("=");
        String token = split[1];
        System.err.println("获取到的token：" + token);
        return token;
    }

    public void downLoad(String token,String cookie,String userAgent){
        // 创建httpclient实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpget实例
        CloseableHttpResponse pictureResponse = null;
        CloseableHttpResponse response = null;

        String downLoadUrl = "https://pic.netbian.com/e/extend/downpic.php?token=" + token;

        String diskPath = "/Users/aimo/photo/new/";
        String fileName = diskPath + UUID.randomUUID().toString() + ".jpg";

        HttpGet picGet = new HttpGet(downLoadUrl);
        picGet.addHeader("cookie",cookie);
        picGet.addHeader("user-agent",userAgent);
        try {
            pictureResponse = httpclient.execute(picGet);
            HttpEntity pictureEntity = pictureResponse.getEntity();
            InputStream inputStream = pictureEntity.getContent();

            // 使用 common-io 下载图片到本地，注意图片名不能重复 ✔
            FileUtils.copyToFile(inputStream, new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
